<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
	</head>
	<body>
		<div id="app">
			<h1>购物车</h1>
			<!-- 
			步骤:
			1. 定义购物车里的数据
			2. 显示购物车列表
			3. 改变数量		
			4. 改变总数量、总价格
			5. 全选功能
			-->
			
			
			
			<table>
				<tr v-for="(cart,i) in cartList" :key="cart.id">
					<td v-if="cart.check">
						<input type="checkbox" checked @click="checkBtn(i)"/>
					</td>
					<td v-else>
						<input type="checkbox" @click="checkBtn(i)" />
					</td>
					
					<td>
						<img :src="cart.imgurl" />
					</td>
					<td>
						{{cart.title}} &nbsp;&nbsp;{{cart.price}}
					</td>
					<td>
						<button type="button" @click="sub(i)">-</button>
						{{cart.num}}
						<button type="button" @click="add(i)">+</button>
					</td>
				</tr>
			</table>
			<div>
				<input type="checkbox" @click="selAll"/>全选<br />
				总数量:{{allNum}}<br />
				总价格:{{allPrice}}<br />
			</div>
		</div>

		<script>
			const vm = Vue.createApp({
				data() {
					return {
						allNum:0,
						allPrice:0,
						cartList:[
							{
								id:1,
								title:"瓜子",
								imgurl:"../images/logo.png",
								price:30,
								num:1,
								check:false,
							},
							{
								id:2,
								title:"花生",
								imgurl:"../images/logo.png",
								price:15,
								num:2,
								check:true,
							},
							{
								id:3,
								title:"西瓜子",
								imgurl:"../images/logo.png",
								price:20,
								num:1,
								check:true,
							}
						]
					}
				},
				methods:{
					checkBtn(i)
					{
						console.log(i);
						this.cartList[i].check = !this.cartList[i].check;
						this.calcAllNum();
						this.calcAllPrice();
					},
					sub(i){
						this.cartList[i].num--;
						this.calcAllNum();
						this.calcAllPrice();
					},
					add(i)
					{
						this.cartList[i].num++;
						this.calcAllNum();
						this.calcAllPrice();
					},
					calcAllNum()
					{
						var num = 0;
						for(var i in this.cartList)
						{
							if(this.cartList[i].check)
							{
								num+= this.cartList[i].num;
							}
						}
						this.allNum = num;
					},
					calcAllPrice()
					{
						var price = 0;
						for(var i in this.cartList)
						{
							if(this.cartList[i].check)
							{
								price+= this.cartList[i].price * this.cartList[i].num;
							}
						}
						this.allPrice = price; 
					},
					selAll(e) 
					{
						console.log(e);
						// e 事件对象
						// e.target 触发事件的对象
						
						if(e.target.checked)
						{
							console.log("选中所有");
							
							for(var i in this.cartList)
							{
								this.cartList[i].check = true;
							}
						}
						else
						{
							console.log("取消全选");
							
							for(var i in this.cartList)
							{
								this.cartList[i].check = false;
							}
						}
						
						this.calcAllNum();
						this.calcAllPrice();
					}
				}
			})
			vm.mount("#app");
		</script>
	</body>
</html>
